import { createStore } from "vuex";
import request from "@/util/request";
import { getUserInfo } from "@/api/user";
export default createStore({
  state: {
    // tabs
    editableTabsValue: sessionStorage.getItem("editableTabsValue") || "/index",
    editableTabs: JSON.parse(sessionStorage.getItem("editableTabs")) || [
      {
        title: "首页",
        name: "/index",
      },
    ],
    // 菜单
    menuList: JSON.parse(sessionStorage.getItem("menuList")) || [],
    // 动态路由
    dynamicRoutes: [],
    // 用户信息
    userInfo: JSON.parse(sessionStorage.getItem("userInfo")) || "",
  },
  mutations: {
    // tabs
    ADD_TABS: (state, tab) => {
      if (state.editableTabs.findIndex((e) => e.name === tab.path) === -1) {
        state.editableTabs.push({
          // id: tab.id,
          title: tab.name,
          name: tab.path,
        });
      }
      state.editableTabsValue = tab.path;
      sessionStorage.setItem("editableTabsValue", state.editableTabsValue);
      sessionStorage.setItem(
        "editableTabs",
        JSON.stringify(state.editableTabs)
      );
    },
    ALERT_TABS: (state, tabs) => {
      state.editableTabsValue = tabs[1];
      state.editableTabs = tabs[0];
      console.log("tabs", tabs[0], state.editableTabsValue);

      sessionStorage.setItem("editableTabsValue", state.editableTabsValue);
      sessionStorage.setItem(
        "editableTabs",
        JSON.stringify(state.editableTabs)
      );
    },
    RESET_TABS: (state) => {
      state.editableTabsValue = "/index";
      state.editableTabs = [
        {
          title: "首页",
          name: "/index",
        },
      ];
      sessionStorage.removeItem("editableTabsValue");
      sessionStorage.removeItem("editableTabs");
    },

    // 菜单
    ADD_MENU: (state, menuList) => {
      state.menuList.push(...menuList);
      console.log("menu", state.menuList);
    },
    RESET_MENU: (state) => {
      state.menuList = [];
    },

    // 路由
    SET_DYNAMICROUTES(state, routes) {
      state.dynamicRoutes = routes;
    },
    GET_USER_INFO: (state) => {
      state.userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo;
    },
  },
  actions: {
    async getUserInfo({ commit }, userId) {
      try {
        let result = await getUserInfo({ userId: userId });
        console.log("result123", result);
        if (result.status === 200) {
          commit("SET_USER_INFO", result.data);
        } else {
          ElMessage.error("获取用户信息失败");
        }
      } catch (error) {
        console.log(123);
      }
    },
  },
});
